<template>
  <div class="systemConfig">
    <el-form
      ref="baseForm"
      :model="baseForm"
      :rules="rules"
      label-width="140px"
    >
      <el-tabs
        v-model="editableTabsValue"
        type="card"
        editable
        @edit="handleTabsEdit"
      >
        <template v-for="(item, index) in baseForm.dingCom">
          <el-tab-pane
            v-if="item.action && item.action == 'add'"
            :label="'新增'"
            :name="index + ''"
            :key="index"
          >
            <span slot="label">新增</span>
            <div style="max-height: 600px; overflow-y: auto">
              <el-row :gutter="20" style="margin-top: 15px">
                <el-col :span="12" :offset="6" :pull="6">
                  <el-form-item
                    label="企业名称"
                    :prop="'dingCom.' + index + '.accountConfigId'"
                    :rules="rules.name"
                  >
                    <MsgAccountDialog
                      v-model="item.accountConfigId"
                      :title="item.name"
                      :messageType="'4'"
                      :itemIndex="index"
                      :clearable="false"
                      @change="onAccountChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="CorpId"
                    :prop="'dingCom.' + index + '.corpId'"
                    :rules="rules.corpId"
                  >
                    <el-input
                      disabled
                      v-model="item.corpId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="API Token"
                    :prop="'dingCom.' + index + '.apiToken'"
                    :rules="rules.apiToken"
                  >
                    <el-input
                      disabled
                      v-model="item.apiToken"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="App ID"
                    :prop="'dingCom.' + index + '.appId'"
                    :rules="rules.appId"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="应用唯一标识（UnifiedAppId）,可用于获取应用的基本信息、配置信息、数据等，后续会逐步替代原内部应用AgentId和三方应用AppId"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      App ID
                    </span>
                    <el-input
                      disabled
                      v-model="item.appId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="Client ID"
                    :prop="'dingCom.' + index + '.clientId'"
                    :rules="rules.clientId"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="(原 AppKey 和 SuiteKey)"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      Client ID
                    </span>
                    <el-input
                      disabled
                      v-model="item.clientId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="Client Secret"
                    :prop="'dingCom.' + index + '.clientSecrent'"
                    :rules="rules.clientSecret"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="(原 AppSecret 和 SuiteSecret)"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      Client Secret
                    </span>
                    <el-input
                      disabled
                      v-model="item.clientSecrent"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6" :pull="6">
                  <el-form-item
                    label="组织上级"
                    :prop="'dingCom.' + index + '.orgParent'"
                  >
                    <el-select
                      v-model="item.orgParent"
                      clearable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="company in companyList"
                        :key="company.fullName"
                        :label="company.fullName"
                        :value="company.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item label="触发事件">
                    <el-table :data="item.ddEvents" :border="true">
                      <el-table-column
                        prop="select"
                        label=""
                        width="50"
                        :align="'center'"
                      >
                        <template slot-scope="scope">
                          <el-checkbox v-model="scope.row.select" />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="title"
                        label="触发事件"
                        width="200"
                      />
                      <el-table-column prop="desc" label="描述" />
                    </el-table>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="同步反馈">
                    <el-table :data="ddResults" :border="true">
                      <el-table-column prop="synType" label="同步类型" />
                      <el-table-column prop="recordTotal" label="总数" />
                      <el-table-column
                        prop="synSuccessCount"
                        label="同步成功数"
                      />
                      <el-table-column prop="synFailCount" label="同步失败数" />
                      <el-table-column prop="unSynCount" label="未同步数" />
                      <el-table-column
                        prop="synDate"
                        label="同步时间"
                        :formatter="jsbos.tableDateFormat"
                      />
                      <el-table-column label="操作" width="180">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            @click="syncDing(scope.row, item)"
                            :loading="scope.row.loading"
                            >同步</el-button
                          >

                          <el-button
                            size="mini"
                            type="text"
                            @click="syncDingToSys(scope.row, item)"
                            :loading="scope.row.loading"
                            >拉取</el-button
                          >
                          <el-button
                            size="mini"
                            type="text"
                            @click="syncDingHlToSys(scope.row, item)"
                            :loading="scope.row.loading"
                            >企业互联</el-button
                          >
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane
            v-else
            :label="item.name"
            :name="index + ''"
            :key="index + '1'"
          >
            <span slot="label">{{ item.name }}</span>
            <div style="max-height: 600px; overflow-y: auto">
              <el-row :gutter="20" style="margin-top: 15px">
                <el-col :span="12" :offset="6" :pull="6">
                  <el-form-item
                    label="企业名称"
                    :prop="'dingCom.' + index + '.accountConfigId'"
                    :rules="rules.name"
                  >
                    <MsgAccountDialog
                      v-model="item.accountConfigId"
                      :title="item.name"
                      :messageType="'4'"
                      :itemIndex="index"
                      :clearable="false"
                      @change="onAccountChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="CorpId"
                    :prop="'dingCom.' + index + '.corpId'"
                    :rules="rules.corpId"
                  >
                    <el-input
                      disabled
                      v-model="item.corpId"
                      placeholder="请输入CorpId"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="API Token"
                    :prop="'dingCom.' + index + '.apiToken'"
                    :rules="rules.apiToken"
                  >
                    <el-input
                      disabled
                      v-model="item.apiToken"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="App ID"
                    :prop="'dingCom.' + index + '.appId'"
                    :rules="rules.appId"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="应用唯一标识（UnifiedAppId）,可用于获取应用的基本信息、配置信息、数据等，后续会逐步替代原内部应用AgentId和三方应用AppId"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      App ID
                    </span>
                    <el-input
                      disabled
                      v-model="item.appId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="AgentId"
                    :prop="'dingCom.' + index + '.agentId'"
                    :rules="rules.agentId"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="原企业内部应用AgentId"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      AgentId
                    </span>
                    <el-input
                      disabled
                      v-model="item.agentId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="Client ID"
                    :prop="'dingCom.' + index + '.clientId'"
                    :rules="rules.clientId"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="(原 AppKey 和 SuiteKey)"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      Client ID
                    </span>
                    <el-input
                      disabled
                      v-model="item.clientId"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="Client Secret"
                    :prop="'dingCom.' + index + '.clientSecrent'"
                    :rules="rules.clientSecret"
                  >
                    <span slot="label">
                      <el-tooltip
                        content="(原 AppSecret 和 SuiteSecret)"
                        placement="top"
                      >
                        <i
                          class="icon-ym icon-ym-header-about"
                          style="font-size: 14px"
                        ></i>
                      </el-tooltip>
                      Client Secret
                    </span>
                    <el-input
                      disabled
                      v-model="item.clientSecrent"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6" :pull="6">
                  <el-form-item
                    label="组织上级"
                    :prop="'dingCom.' + index + '.orgParent'"
                  >
                    <el-select
                      v-model="item.orgParent"
                      clearable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="company in companyList"
                        :key="company.fullName"
                        :label="company.fullName"
                        :value="company.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col>
                  <el-form-item label="触发事件">
                    <el-table :data="item.ddEvents" :border="true">
                      <el-table-column
                        prop="select"
                        label=""
                        width="50"
                        :align="'center'"
                      >
                        <template slot-scope="scope">
                          <el-checkbox v-model="scope.row.select" />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="title"
                        label="触发事件"
                        width="200"
                      />
                      <el-table-column prop="desc" label="描述" />
                    </el-table>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="同步反馈">
                    <el-table :data="ddResults" :border="true">
                      <el-table-column prop="synType" label="同步类型" />
                      <el-table-column prop="recordTotal" label="总数" />
                      <el-table-column
                        prop="synSuccessCount"
                        label="同步成功数"
                      />
                      <el-table-column prop="synFailCount" label="同步失败数" />
                      <el-table-column prop="unSynCount" label="未同步数" />
                      <el-table-column
                        prop="synDate"
                        label="同步时间"
                        :formatter="jsbos.tableDateFormat"
                      />
                      <el-table-column label="操作" width="180">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            @click="syncQy(scope.row, item)"
                            :loading="scope.row.loading"
                            >同步</el-button
                          >

                          <el-button
                            size="mini"
                            type="text"
                            @click="syncQyToSys(scope.row, item)"
                            :loading="scope.row.loading"
                            >拉取</el-button
                          >
                          <el-button
                            size="mini"
                            type="text"
                            @click="syncQyHlToSys(scope.row, item)"
                            :loading="scope.row.loading"
                            >企业互联</el-button
                          >
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </template>
      </el-tabs>
      <div style="margin: 10px 0">
        <el-button
          type="primary"
          size="small"
          :loading="btnLoading"
          class="saveBtn"
          @click="submitForm('DingComConfig')"
          >保存</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import MsgAccountDialog from "./msgAccountDialog";
import { getInfo } from "@/views/message/api/mcAccountConfig";
import {
  getSynThirdTotal,
  updateSystemConfig,
  synAllOrganizeSysToDing,
  synAllUserSysToDing,
  synDingToAllOrganizeSys,
  synDingToAllUserSys,
} from "@/api/system/sysConfig";
import { getAllCompanyList } from "@/api/permission/organize";
import { isEmpty } from "@/utils/isEmpty";
const CATEGORY = "DingComConfig";
export default {
  name: "SysConfigDingMutilSetting",
  components: { MsgAccountDialog },
  props: {
    tabsData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    var validateDingCropId = (rule, value, callback) => {
      let index = rule.fullField.split(".")[1];
      if (this.$isEmpty(value)) {
        callback(new Error("CorpId不能为空"));
      } else if (
        !this.$isEmpty(
          this.baseForm.dingCom.filter((v, i) => {
            return v.corpId == value && i != index;
          })
        )
      ) {
        callback(new Error("有重复的CorpId"));
      } else {
        callback();
      }
    };
    return {
      btnLoading: false,
      DingConfig: {
        accountConfigId: "",
        name: "",
        corpId: "",
        apiToken: "",
        appId: "", // App ID
        agentId: "", // AgentId
        clientId: "", // Client ID (原 AppKey 和 SuiteKey)
        clientSecrent: "", // Client Secret (原 AppSecret 和 SuiteSecret)
        dingSynIsSynOrg: "", // 同步钉钉组织
        dingSynIsSynUser: "", // 同步钉钉用户
        orgParent: "", //组织上级
        action: "add", //action属性（‘view’：查看状态，'edit’编辑状态，'add’新增状态）
      },
      baseForm: {
        dingCom: this.tabsData,
      },
      rules: {
        accountConfigId: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        name: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        corpId: [
          { required: true, message: "CorpId不能为空", trigger: "blur" },
          {
            required: true,
            validator: validateDingCropId,
            trigger: "blur",
          },
        ],
        apiToken: [
          { required: true, message: "API Token不能为空", trigger: "blur" },
        ],
        appId: [{ required: true, message: "App ID不能为空", trigger: "blur" }],
        agentId: [
          { required: true, message: "AgentId不能为空", trigger: "blur" },
        ],
        clientId: [
          { required: true, message: "企业号ID不能为空", trigger: "blur" },
        ],
        clientSecret: [
          { required: true, message: "凭证秘钥不能为空", trigger: "blur" },
        ],
      },
      editableTabsValue: 0,
      tabIndex: 0,
      companyList: [],
      ddEvents: [
        {
          select: false,
          title: "启用同步组织",
          desc: "新增、删除、修改组织信息触发同步组织事件",
        },
        {
          select: false,
          title: "启用同步用户",
          desc: "新增、删除、修改用户信息触发同步用户事件",
        },
      ],
      ddResults: [
        {
          recordTotal: "",
          synDate: "",
          synFailCount: "",
          synSuccessCount: "",
          synType: "组织",
          unSynCount: "",
        },
        {
          recordTotal: "",
          synDate: "",
          synFailCount: "",
          synSuccessCount: "",
          synType: "用户",
          unSynCount: "",
        },
      ],
    };
  },
  watch: {
    tabsData() {
      this.baseForm.dingCom = JSON.parse(JSON.stringify(this.tabsData));
      this.initData();
    },
  },
  created() {
    this.initData();
    this.allCompanyList();
  },
  mounted() {
    // 第三方类型(1:企业微信;2:钉钉)
    this.querySynThirdTotal(2);
  },
  methods: {
    /**账号change事件 */
    onAccountChange(id, item, index) {
      if (!id) return (this.baseForm.dingCom[index].accountName = "");
      this.baseForm.dingCom[index].accountConfigId = item.id;
      this.baseForm.dingCom[index].name = item.fullName;
      this.settingAccount(this.baseForm.dingCom[index]);
    },
    settingAccount(item) {
      getInfo(item.accountConfigId).then((res) => {
        this.$set(item, "corpId", res.data.enterpriseId);
        this.$set(item, "apiToken", res.data.bearer);
        this.$set(item, "appId", res.data.appId); // App ID
        this.$set(item, "agentId", res.data.agentId); // AgentId
        this.$set(item, "clientId", res.data.appKey); // Client ID (原 AppKey 和 SuiteKey)
        this.$set(item, "clientSecrent", res.data.appSecret); // Client Secret (原 AppSecret 和 SuiteSecret)
      });
    },
    syncDing(row, item) {
      row.loading = true;
      item.qyhCorpId = item.clientId;
      item.qyhCorpSecret = item.clientSecrent;
      const method =
        row.synType == "组织" ? synAllOrganizeSysToDing : synAllUserSysToDing;
      method(item)
        .then((res) => {
          row.recordTotal = res.data.recordTotal;
          row.synDate = res.data.synDate;
          row.synFailCount = res.data.synFailCount;
          row.synSuccessCount = res.data.synSuccessCount;
          row.synType = res.data.synType;
          row.unSynCount = res.data.unSynCount;
          row.loading = false;
          this.$message({
            message: "同步成功",
            type: "success",
            duration: 1500,
          });
        })
        .catch(() => {
          row.loading = false;
        });
    },
    syncDingToSys(row, item) {
      row.loading = true;
      item.qyhCorpId = item.clientId;
      item.qyhCorpSecret = item.clientSecrent;
      const method =
        row.synType == "组织" ? synDingToAllOrganizeSys : synDingToAllUserSys;
      method(item)
        .then((res) => {
          row.recordTotal = res.data.recordTotal;
          row.synDate = res.data.synDate;
          row.synFailCount = res.data.synFailCount;
          row.synSuccessCount = res.data.synSuccessCount;
          row.synType = res.data.synType;
          row.unSynCount = res.data.unSynCount;
          row.loading = false;
          this.$message({
            message: "同步成功",
            type: "success",
            duration: 1500,
          });
        })
        .catch(() => {
          row.loading = false;
        });
    },
    querySynThirdTotal(type) {
      getSynThirdTotal(type).then((res) => {
        let list = res.data.map((o) => ({ loading: false, ...o }));
        this.ddResults = list;
      });
    },
    initData() {
      if (this.baseForm.dingCom && this.baseForm.dingCom.length != 0) {
        //处理数据，为已有数据添加action:'edit'
        this.baseForm.dingCom.map((item) => {
          this.$set(
            item,
            "ddEvents",
            JSON.parse(JSON.stringify(this.ddEvents))
          );
          item.ddEvents[0].select =
            item.qyhIsSynOrg && item.qyhIsSynOrg == 1 ? true : false;
          item.ddEvents[1].select =
            item.qyhIsSynUser && item.qyhIsSynUser == 1 ? true : false;
          this.$set(item, "action", "edit");

          this.settingAccount(item);
          return item;
        });
      } else {
        this.$set(this.baseForm, "dingCom", []);
        let DingConfig = JSON.parse(JSON.stringify(this.DingConfig));
        this.$set(
          DingConfig,
          "ddEvents",
          JSON.parse(JSON.stringify(this.ddEvents))
        );
        this.baseForm.dingCom.push(DingConfig);
      }
    },
    //对部分表单字段进行校验
    validateField(form, index) {
      let result = true;
      for (let item of this.$refs[form].fields) {
        if (item.prop.split(".")[1] == index) {
          this.$refs[form].validateField(item.prop, (error) => {
            if (error != "") {
              result = false;
            }
          });
        }
        if (!result) break;
      }
      return result;
    },

    //对部分表单字段进行重置
    resetField(form, index) {
      this.$refs[form].fields.forEach((item) => {
        if (item.prop.split(".")[1] == index) {
          item.resetField();
        }
      });
    },
    /**保存 */
    submitForm(category) {
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          // 基础设置
          if (category == CATEGORY) {
            var jsonForm = this.dataList();
            var form = {
              category: CATEGORY,
              list: [
                {
                  name: "钉钉企业信息",
                  key: "dingCom",
                  value: jsonForm,
                },
              ],
            };
            updateSystemConfig(form)
              .then((res) => {
                this.$message({
                  message: res.msg,
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.$emit("refresh");
                    this.btnLoading = false;
                  },
                });
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        } else {
          this.$message({
            message: "表单校验未通过，请核对所有钉钉配置信息",
            type: "error",
            duration: 1000,
          });
          return false;
        }
      });
    },
    dataList() {
      var paramForm = JSON.parse(JSON.stringify(this.baseForm.dingCom));
      paramForm.map((item) => {
        item.qyhIsSynOrg = item.ddEvents[0].select ? 1 : 0;
        item.qyhIsSynUser = item.ddEvents[1].select ? 1 : 0;
        this.$delete(item, "ddEvents");
        this.$delete(item, "ddResults");
        this.$delete(item, "action");

        this.$delete(item, "corpId");
        this.$delete(item, "apiToken");
        this.$delete(item, "appId");
        this.$delete(item, "agentId");
        this.$delete(item, "clientId");
        this.$delete(item, "clientSecrent");
        this.$delete(item, "dingComputerUrl");
        this.$delete(item, "dingMobileUrl");
      });
      return JSON.stringify(paramForm);
    },
    allCompanyList() {
      getAllCompanyList().then((res) => {
        this.companyList = res.data.list;
      });
    },
    handleTabsEdit(targetName, action) {
      if (action === "add") {
        let dingComLength = this.baseForm.dingCom.length;
        let DingConfig = JSON.parse(JSON.stringify(this.DingConfig));
        this.$set(
          DingConfig,
          "ddEvents",
          JSON.parse(JSON.stringify(this.ddEvents))
        );
        this.baseForm.dingCom.push(DingConfig);
        this.editableTabsValue = dingComLength + "";
      }
      if (action === "remove") {
        this.editableTabsValue = targetName;
        let tabs = JSON.parse(JSON.stringify(this.baseForm.dingCom));
        let targetTab;
        let nextActive;
        tabs.forEach((tab, index) => {
          let tempIndex = index + "";
          if (tempIndex === targetName) {
            targetTab = tab;
            nextActive = (tabs[index + 1] ? index : index - 1) + "";
            // let nextTab = tabs[index + 1] || tabs[index - 1];
          }
        });
        if (targetTab) {
          let msg = `您确定要删除\n企业名称[${targetTab.name}]\nCorpId[${targetTab.corpId}]吗？`;
          this.$confirm(msg, "提示", {
            type: "warning",
          })
            .then(() => {
              this.baseForm.dingCom = tabs.filter(
                (tab, index) => index != targetName
              );
              this.editableTabsValue = nextActive;
            })
            .catch(() => {});
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.systemConfig {
  padding: 0;

  .saveBtn {
    width: 100px;
  }
}
</style>
